import Router from 'koa-router';
import { pool } from '../../config/database';
import { authMiddleware } from '../../middleware/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { ApiResponse, ComputerConfig, ComputerConfigCreateInput, ComputerConfigUpdateInput, ComputerConfigQueryParams, JwtPayload } from '../../types';

const router = new Router({ prefix: '/api/product' });

// C端产品数据格式化函数
const formatProductForClient = (product: any) => {
  // 解析JSON字段
  const parseJsonField = (field: any) => {
    if (!field) return null;
    if (typeof field === 'object') return field;
    try {
      return JSON.parse(field);
    } catch (e) {
      return null;
    }
  };

  // 处理features字段 - 转换为字符串数组格式（C端兼容）
  let features = parseJsonField(product.features);
  if (Array.isArray(features)) {
    // 如果是对象数组，提取title字段
    if (features.length > 0 && typeof features[0] === 'object' && features[0] !== null) {
      features = features.map((feature: any) => feature.title || feature.name || String(feature));
    }
    // 如果已经是字符串数组，保持不变
  } else {
    features = [];
  }

  return {
    ...product,
    specifications: parseJsonField(product.specifications),
    features: features, // C端返回字符串数组
    images: parseJsonField(product.images),
    tags: parseJsonField(product.tags),
    // 转换布尔值字段
    isFeatured: Boolean(product.isFeatured),
    isHot: Boolean(product.isHot)
  };
};

// 测试路由 - 查看数据库表
router.get('/test-tables', async (ctx) => {
  try {
    const [tables] = await pool.query('SHOW TABLES') as [RowDataPacket[], any];
    ctx.body = {
      success: true,
      data: tables,
      message: '数据库表列表'
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '查看表失败：' + error.message
    };
  }
});

// 测试路由 - 查看表结构
router.get('/test-structure', async (ctx) => {
  try {
    const [structure] = await pool.query('DESCRIBE computer_configs') as [RowDataPacket[], any];
    ctx.body = {
      success: true,
      data: structure,
      message: 'computer_configs 表结构'
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '查看表结构失败：' + error.message
    };
  }
});

// 测试路由 - 查看products表结构
router.get('/test-products-structure', async (ctx) => {
  try {
    const [structure] = await pool.query('DESCRIBE products') as [RowDataPacket[], any];
    ctx.body = {
      success: true,
      data: structure,
      message: 'products 表结构'
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '查看products表结构失败：' + error.message
    };
  }
});

// 测试路由 - 查看products表数据样例
router.get('/test-products-data', async (ctx) => {
  try {
    const [data] = await pool.query('SELECT * FROM products LIMIT 5') as [RowDataPacket[], any];
    ctx.body = {
      success: true,
      data: data,
      message: 'products 表数据样例'
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '查看products表数据失败：' + error.message
    };
  }
});

// 测试路由 - 检查产品价格字段
router.get('/test-price-data', async (ctx) => {
  try {
    const [products] = await pool.query('SELECT id, name, price, original_price FROM products LIMIT 10') as [RowDataPacket[], any];
    
    const analysis = products.map(product => ({
      id: product.id,
      name: product.name,
      price: product.price,
      price_type: typeof product.price,
      price_is_null: product.price === null,
      price_is_undefined: product.price === undefined,
      original_price: product.original_price,
      original_price_type: typeof product.original_price
    }));
    
    ctx.body = {
      success: true,
      data: analysis,
      message: '产品价格数据分析'
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '查看产品价格数据失败：' + error.message
    };
  }
});

// 调试路由 - 测试简单查询
router.get('/debug-simple', async (ctx) => {
  try {
    // 最简单的查询，不带参数
    const [products1] = await pool.query('SELECT * FROM products LIMIT 2') as [RowDataPacket[], any];
    
    // 带一个参数的查询
    const [products2] = await pool.query('SELECT * FROM products LIMIT ?', [2]) as [RowDataPacket[], any];
    
    // 带多个参数的查询
    const [products3] = await pool.query('SELECT * FROM products WHERE status = ? LIMIT ?', ['active', 2]) as [RowDataPacket[], any];
    
    ctx.body = {
      success: true,
      data: {
        test1_no_params: products1.length,
        test2_one_param: products2.length, 
        test3_two_params: products3.length
      },
      message: '调试测试成功'
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '调试测试失败：' + error.message
    };
  }
});

// 获取热门产品 - 前端期望的路径
router.get('/getHot', async (ctx) => {
  try {
    const limit = parseInt(ctx.query.limit as string) || 4;
    
    const [products] = await pool.query(
      'SELECT * FROM products WHERE isHot = ? AND stock > ? AND status = ? ORDER BY sales DESC, rating DESC, created_at DESC LIMIT ?',
      [1, 0, 'active', limit]
    ) as [RowDataPacket[], any];
    
    ctx.body = {
      success: true,
      data: products,
      message: '获取热门产品成功'
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取热门产品失败：' + error.message
    };
  }
});

// 获取热门产品
router.get('/hot', async (ctx) => {
  try {
    const limit = parseInt(ctx.query.limit as string) || 4;
    
    const [products] = await pool.query(
      'SELECT * FROM products WHERE isHot = ? AND stock > ? AND status = ? ORDER BY sales DESC, rating DESC, created_at DESC LIMIT ?',
      [1, 0, 'active', limit]
    ) as [RowDataPacket[], any];
    
    ctx.body = {
      success: true,
      data: products
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取热门产品失败：' + error.message
    };
  }
});

// 获取推荐产品
router.get('/featured', async (ctx) => {
  try {
    const limit = parseInt(ctx.query.limit as string) || 4;
    
    const [products] = await pool.query(
      'SELECT * FROM products WHERE isFeatured = ? AND stock > ? AND status = ? ORDER BY created_at DESC LIMIT ?',
      [1, 0, 'active', limit]
    ) as [RowDataPacket[], any];
    
    // 格式化产品数据，确保features为字符串数组
    const formattedProducts = products.map(formatProductForClient);
    
    ctx.body = {
      success: true,
      data: formattedProducts
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取推荐产品失败：' + error.message
    };
  }
});

// 根据分类获取产品
router.get('/category/:category', async (ctx) => {
  try {
    const { category } = ctx.params;
    const { page = 1, limit = 10 } = ctx.query;
    const offset = (Number(page) - 1) * Number(limit);
    
    const [products] = await pool.query(
      'SELECT * FROM products WHERE category_id = ? AND stock > ? AND status = ? ORDER BY created_at DESC LIMIT ? OFFSET ?',
      [category, 0, 'active', Number(limit), offset]
    ) as [RowDataPacket[], any];
    
    ctx.body = {
      success: true,
      data: products
    } as ApiResponse<ComputerConfig[]>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取分类产品失败：' + error.message
    } as ApiResponse;
  }
});

// 获取产品列表
router.get('/', async (ctx) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      min_price, 
      max_price, 
      sort = 'newest', 
      search,
      category,
      category_id 
    } = ctx.query as ComputerConfigQueryParams;
    
    const offset = (Number(page) - 1) * Number(limit);
    
    // 构建WHERE条件
    let whereConditions = [`status = 'active'`];
    let queryParams: any[] = [];
    
    // 价格过滤
    if (min_price !== undefined) {
      whereConditions.push('price >= ?');
      queryParams.push(Number(min_price));
    }
    
    if (max_price !== undefined) {
      whereConditions.push('price <= ?');
      queryParams.push(Number(max_price));
    }
    
    // 搜索功能
    if (search) {
      whereConditions.push('(name LIKE ? OR description LIKE ? OR short_description LIKE ?)');
      const searchTerm = `%${search}%`;
      queryParams.push(searchTerm, searchTerm, searchTerm);
    }
    
    // 分类过滤
    if (category_id) {
      whereConditions.push('category_id = ?');
      queryParams.push(category_id);
    }
    
    // 分类过滤 - 支持category字段
    if (category) {
      whereConditions.push('category = ?');
      queryParams.push(category);
    }
    
    // 构建ORDER BY子句
    let orderBy = 'created_at DESC'; // 默认按创建时间降序
    
    switch (sort) {
      case 'price_asc':
        orderBy = 'price ASC';
        break;
      case 'price_desc':
        orderBy = 'price DESC';
        break;
      case 'sales_desc':
        orderBy = 'sales DESC, created_at DESC';
        break;
      case 'newest':
        orderBy = 'created_at DESC';
        break;
      default:
        orderBy = 'created_at DESC';
    }
    
    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';
    
    // 获取产品列表
    const [products] = await pool.query(
      `SELECT * FROM products ${whereClause} ORDER BY ${orderBy} LIMIT ? OFFSET ?`,
      [...queryParams, Number(limit), offset]
    ) as [RowDataPacket[], any];
    
    // 获取总数
    const [countResult] = await pool.query(
      `SELECT COUNT(*) as total FROM products ${whereClause}`,
      queryParams
    ) as [RowDataPacket[], any];
    
    const total = countResult[0].total;
    const totalPages = Math.ceil(total / Number(limit));
    
    // 格式化产品数据，确保features为字符串数组
    const formattedProducts = products.map(formatProductForClient);
    
    ctx.body = {
      success: true,
      data: formattedProducts,
      meta: {
        total: total,
        page: Number(page),
        limit: Number(limit),
        totalPages: totalPages
      }
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取产品列表失败：' + error.message
    };
  }
});

// 获取产品详情
router.get('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    
    const [products] = await pool.query(
      `SELECT * FROM products WHERE id = ? AND status = 'active'`,
      [id]
    ) as [RowDataPacket[], any];
    
    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '产品不存在'
      } as ApiResponse;
      return;
    }
    
    const product = products[0] as ComputerConfig;
    
    ctx.body = {
      success: true,
      data: product
    } as ApiResponse<ComputerConfig>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取产品详情失败：' + error.message
    } as ApiResponse;
  }
});

// 创建产品（需要认证）
router.post('/', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const {
      name,
      slug,
      short_description,
      description,
      specifications,
      features,
      images,
      tags,
      tabs,
      isFeatured = 0,
      isHot = 0,
      meta_title
    } = ctx.request.body as any;
    
    if (!name) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '缺少必填字段（名称）'
      } as ApiResponse;
      return;
    }
    
    // 生成slug（如果没有提供）
    const finalSlug = slug || name.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]/g, '-').replace(/-+/g, '-');
    
    // 创建产品
    const [result] = await pool.query(
      `INSERT INTO products (
        name, slug, category_id, short_description, description, specifications, features, images, tags,
        status, isFeatured, isHot, meta_title
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        name,
        finalSlug,
        1, // 默认 category_id
        short_description || null,
        description || null,
        specifications ? JSON.stringify(specifications) : null,
        features ? JSON.stringify(features) : null,
        images ? JSON.stringify(images) : null,
        tags ? JSON.stringify(tags) : null,
        'active',
        isFeatured,
        isHot,
        meta_title || null
      ]
    ) as [ResultSetHeader, any];
    
    // 获取创建的产品信息
    const [products] = await pool.query(
      `SELECT * FROM products WHERE id = ?`,
      [result.insertId]
    ) as [RowDataPacket[], any];
    
    // 格式化产品数据，确保features为字符串数组
    const formattedProduct = formatProductForClient(products[0]);
    
    ctx.body = {
      success: true,
      data: formattedProduct,
      message: '产品创建成功'
    } as ApiResponse<ComputerConfig>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '创建产品失败：' + error.message
    } as ApiResponse;
  }
});

// 更新产品
router.put('/:id', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    const updateData = ctx.request.body as any;
    
    // 检查产品是否存在
    const [products] = await pool.query(
      `SELECT * FROM products WHERE id = ?`,
      [id]
    ) as [RowDataPacket[], any];
    
    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '产品不存在'
      } as ApiResponse;
      return;
    }
    
    // 构建更新字段 - 只更新实际存在的字段
    const updateFields: string[] = [];
    const updateValues: any[] = [];
    
    const allowedFields = ['name', 'slug', 'short_description', 'description', 'specifications', 'features', 'images', 'tags', 'status', 'isFeatured', 'isHot', 'meta_title'];
    
    Object.entries(updateData).forEach(([key, value]) => {
      if (value !== undefined && allowedFields.includes(key)) {
        if (['specifications', 'features', 'images', 'tags'].includes(key)) {
          updateFields.push(`${key} = ?`);
          updateValues.push(JSON.stringify(value));
        } else {
          updateFields.push(`${key} = ?`);
          updateValues.push(value);
        }
      }
    });
    
    if (updateFields.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '没有要更新的字段'
      } as ApiResponse;
      return;
    }
    
    updateValues.push(id);
    
    // 更新产品
    await pool.query(
      `UPDATE products SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
      updateValues
    );
    
    // 获取更新后的产品信息
    const [updatedProducts] = await pool.query(
      `SELECT * FROM products WHERE id = ?`,
      [id]
    ) as [RowDataPacket[], any];
    
    // 格式化产品数据，确保features为字符串数组
    const formattedProduct = formatProductForClient(updatedProducts[0]);
    
    ctx.body = {
      success: true,
      data: formattedProduct,
      message: '产品更新成功'
    } as ApiResponse<ComputerConfig>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '更新产品失败：' + error.message
    } as ApiResponse;
  }
});

// 删除产品
router.delete('/:id', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    
    // 检查产品是否存在
    const [products] = await pool.query(
      `SELECT * FROM products WHERE id = ?`,
      [id]
    ) as [RowDataPacket[], any];
    
    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '产品不存在'
      } as ApiResponse;
      return;
    }
    
    // 删除产品
    await pool.query('DELETE FROM products WHERE id = ?', [id]);
    
    ctx.body = {
      success: true,
      message: '产品删除成功'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '删除产品失败：' + error.message
    } as ApiResponse;
  }
});

export default router; 